import { defineStore } from "pinia";
import { registerinfo, login } from "@/api/login";
import { ref, reactive } from "vue";

type User = {
  username: string; // 用户名，必须是字符串
  password: string; // 密码，必须是字符串
  phone: string; // 电话号码，必须是字符串
  address: string; // 地址，必须是字符串
  email: string; //邮箱
};

export const useUserStore = defineStore(
  "Big-user",
  () => {
    //用户id
    const userId = ref("");
    const username = ref("");
    const usertype = ref(uni.getStorageSync("usertype") || "");
    const information = ref();

    // 定义方法
    const setUserInfo = (newUserId: any, newusername: any) => {
      userId.value = newUserId;
      username.value = newusername;
      uni.setStorageSync("userId", newUserId);
      uni.setStorageSync("username", newusername);
    };
    //修改类型
    const updatetype = (type: any) => {
      usertype.value = type;
      uni.setStorageSync("usertype", type);
      return Promise.resolve();
    };
    //优化注册
    const formregisterData = reactive<User>({ username: "", password: "", phone: "", address: "", email: "" });
    const getregisterdata = async () => {
      const res: any = await registerinfo(formregisterData);
      return res;
    };
    //优化登入 -
    const getloadingdata = async (loginData: any) => {
      const res: any = await login(loginData);
      information.value = res.data;
      return res;
    };
    return {
      information,
      userId,
      setUserInfo,
      formregisterData,
      getregisterdata,
      getloadingdata,
      usertype: usertype.value || undefined,
      updatetype: updatetype || undefined,
    };
  },
  {
    persist: true,
  }
);
